<template>
  <div>
    <!-- 面包屑导航 -->
    <UseBreadcrumb>
      <template>
        <el-breadcrumb-item
          v-for="item of ['商品管理', '商品分类']"
          :key="item"
          >{{ item }}</el-breadcrumb-item
        >
      </template>
    </UseBreadcrumb>
    <el-card>
      <el-button type="primary" @click="showAddCategory">添加类别</el-button>
      <!-- 商品类别表格 -->
      <tree-table
        class="tree_table"
        :data="categoryList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :border="true"
      >
        <template slot="isEffective" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_cat_deleted"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="isSort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="options">
          <el-button type="primary" size="mini" icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button type="danger" size="mini" icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 商品类别分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[ 5,20, 30, 400]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加类别的对话框 -->
    <el-dialog title="添加类别" :visible.sync="addCategoryDialogVisible"
    @close="closeAddCateDialog"
    :close-on-click-modal="false"
    >
      <el-form
        ref="addCategoryRef"
        :model="addCategoryForm"
        :rules="addCategoryRules"
        label-width="80px"
      >
        <el-form-item label="添加类别" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"
          
          ></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 
            options:级联数据源
            props:级联每级配置对象
           -->
 
          <el-cascader
            :clearable="true"
            v-model="selectedCategoryId"
            :options="parentCateList"
            :props="selectedCategory"
            @change="selectedCate"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import UseBreadcrumb from '@/common_components/UseBreadcrumb'
export default {
  data() {
    //添加类别cat_name校验规则
    let checkName = (rule,value,cb) =>{
      let reg = /^[\u2E80-\u9FFF]+$/
      if (!reg.test(value)) {
        cb("请正确输入类别名称")
      }else {
        cb()
      }
    }
    return {
      //商品分类的列表
      categoryList: [],
      //获取商品分类数据的请求参数
      queryInfo: {
        type: 3,
        //页码
        pagenum: 1,
        //每页数据条数
        pagesize: 5,
      },
      //页面数据总条数
      total: 100,
      //商品列表树形表格每列属性
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isEffective',
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'isSort',
        },
        {
          label: '排序',
          type: 'template',
          template: 'options',
        },
      ],
      //控制添加类别对话框的显示/隐藏
      addCategoryDialogVisible: false,
      //添加类别表单对象
      addCategoryForm: {
        //添加类别的名称
        cat_name: '',
        //父级分类的id 0:一级 1:二级 2:三级
        cat_pid: 0,
        //添加分类的等级,默认是一级分类:0
        cat_level: 0,
      },
      //添加类别表单数据验证规则
      addCategoryRules: {
        cat_name: [
          { required: true, message: '请输入类别内容', trigger: 'blur' },
          {validator:checkName,trigger: 'blur' }
        ],
      },
      //父级分类数据列表
      parentCateList: [],
      //选中类别信息对象
      selectedCategory: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        //选中任意一项,可以不用父子相连
        checkStrictly: true,
        //实现多选
        //multiple:true
      },
      //选中类别的Id
      selectedCategoryId: [],
    }
  },
  components: {
    UseBreadcrumb,
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    //获取商品分类列表数据
    async getCategoryList() {
      let {
        data: { data: res, meta },
      } = await this.$api.getCategoryData(this.queryInfo)
      if (meta.status === 200) {
        let { result, total } = res
        this.categoryList = result
        this.total = total
      }
    },
    //监听页面数据展示条数的变化
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCategoryList()
    },
    //监听页面数据页码的变化
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum
      this.getCategoryList()
    },
    //展示添加类别对话框
    showAddCategory() {
      //先获取父级分类的数据
      this.getParentCateList()
      this.addCategoryDialogVisible = true
    },
    //获取父级分类的数据列表
    async getParentCateList() {
      //获取前两级的数据
      let {
        data: { data: res, meta },
      } = await this.$api.getParentCateData({ params: { type: 2 } })
      if (meta.status !== 200) {
        this.$message.error('获取父级分类失败')
      }
      this.parentCateList = res
    },
    //选择的类别一就改变触发
    selectedCate(id) {
      let len = this.selectedCategoryId.length
      //如果选中类别的Id数组长度>0,说明给添加的类别进行了分类,
      console.log(len);
      if (len >0) {
        //添加类别的父id就是选中类别Id数组的最后一项
        this.addCategoryForm.cat_pid = this.selectedCategoryId[len-1]
        //添加类别的level等于选中类别Id数组的长度
        this.addCategoryForm.cat_level = len
      }else if (len <= 0) {
        //如果选中类别Id数组的长度=0,那么没有给添加类别分类,属于第一级
        this.addCategoryForm.cat_pid = 0
        this.addCategoryForm.cat_level = 0
      }
    },
    //监听添加类别对话框关闭事件,关闭后,将添加类别表单置空
    closeAddCateDialog() {
      this.$refs.addCategoryRef.resetFields();
      this.addCategoryForm.cat_pid = 0
      this.addCategoryForm.cat_level = 0
      this.selectedCategoryId = []
    },
    //点击添加类别对话框确定按钮实现添加类别功能
    addCategory() {
      this.$refs.addCategoryRef.validate( async (valid)=>{
        if (valid) {
           console.log(this.addCategoryForm);
           let {data:{_,meta}} = await this.$api.addCategoryData(this.addCategoryForm)
          if (meta.status === 201) {
            this.$message.success('添加成功')
            this.getCategoryList()
            this.addCategoryDialogVisible = false
          }else {
            return this.$message.error('添加失败')
          }
         } 
      })
    }
  },
}
</script>

<style lang="less" scoped>
.tree_table {
  margin-top: 10px;
}
.el-cascader {
  width: 100%;
}
</style>
